<template>
  <div class="table-container">
    <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="姓名">
        <el-input v-model="formInline.user" placeholder="请输入姓名" @input="onSubmit"></el-input>
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="primary" @click="onSubmit">查询</el-button> -->
        <el-button type="primary" @click="tj">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="filterTableRef" class="table-list" row-key="date" :data="tableData" style="width: 100%">
      <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
      <el-table-column prop="password" label="密码" width="180"> </el-table-column>
      <el-table-column prop="rolename" label="角色" width="180"> </el-table-column>

      <el-table-column label="添加时间">
        <template #default="scope">
          <span>
            {{ dateFliter(scope.row.created_time) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="修改时间">
        <template #default="scope">
          <span>
            {{ dateFliter(scope.row.update_time) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">分配角色</el-button>
          <el-button size="mini" type="warning" @click="put(scope.$index, scope.row)">修改</el-button>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="确定删除该条记录吗？" @confirm="handleDelete(scope.$index, scope.row)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :hide-on-single-page="false"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20, 25]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 分配角色 -->
    <el-dialog v-model="dialogVisible" title="分配角色" width="30%" :before-close="handleClose">
      <el-row :gutter="20">
        <!-- <el-col :span="4"></el-col> -->
        <el-col :span="4" style="text-align: right; align-items: center"> 用户名: </el-col>
        <el-col :span="18" style="text-align: left; align-items: center">
          <el-select v-model="datas.username" disabled style="width: 300px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4" style="text-align: right"> 权限: </el-col>
        <el-col :span="18" style="text-align: left">
          <el-select v-model="datavalue" class="m-2" placeholder="Select" style="width: 300px">
            <el-option v-for="item in datalist" :key="item.id" :label="item.rolename" :value="item.id" />
          </el-select>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="fpqd">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改数据 -->
    <el-dialog v-model="dialogVisibles" title="修改" width="30%" :before-close="handleCloses">
      <el-form :model="form" ref="ruleFormRef1" status-icon :rules="rules1">
        <el-form-item label="姓名" prop="xiu">
          <el-input v-model="form.xiu" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibles = false">取消</el-button>
          <el-button type="primary" @click="qd(ruleFormRef1)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加用户 -->
    <el-dialog v-model="dialogVisiblets" title="添加" width="30%" :before-close="handleClose">
      <el-form :model="form" ref="ruleFormRef" status-icon :rules="rules">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tjq(ruleFormRef)">Cancel</el-button>
          <el-button type="primary" @click="tjqd(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import permission from '@/directive/permission'
import Service from '../Login/api/index'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
export default defineComponent({
  name: 'TableList',
  directives: {
    permission
  },
  setup() {
    const ruleFormRef = ref<FormInstance>()
    const ruleFormRef1 = ref<FormInstance>()
    const filterTableRef = ref()
    const dialogVisible = ref(false)
    const dialogVisibles = ref(false)
    const dialogVisiblets = ref(false)
    const xiudata = ref()
    const xiu = ref()
    const datavalue = ref()
    const obj = reactive({
      form: {
        username: '',
        password: '',
        xiu: ''
      }
    })
    const obj1 = reactive({
      id: '',
      datas: {},
      datalist: []
    })
    const state = reactive({
      tableData: [],
      tableDatalist: [],
      currentPage: 1,
      pageSize: 5,
      search: ''
    })
    const datas = async () => {
      const res = await Service.tablelist_datas()
      console.log(res.data)
      total.value = res.data.length
      state.tableData = res.data
      state.tableDatalist = res.data
    }
    datas()
    const formInline = reactive({
      user: '',
      region: ''
    })
    const total = ref()

    const dateFliter = (val: any, format = 'YYYY-MM-DD hh:mm:ss') => {
      if (!isNaN(val)) {
        val = parseInt(val)
      }
      return dayjs(val).format(format)
    }

    onMounted(() => {
      console.dir(filterTableRef.value)
    })
    const handleEdit = async (index: any, row: any) => {
      console.log(row.username)
      obj1.datas = row
      obj1.id = row.id
      const res = await Service.tablelist_qxhq()
      obj1.datalist = res.data

      dialogVisible.value = true
    }
    const put = async (index: any, row: any) => {
      console.log(index, row)
      dialogVisibles.value = true
      xiudata.value = row
      // xiu.value = row.username
      obj.form.xiu = row.username
    }
    const validatePass3 = (rule: any, value: any, callback: any) => {
      console.log(value, 110)
      if (value === '') {
        callback(new Error('姓名不能为空'))
      } else {
        callback()
      }
    }
    const qd = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (valid) {
          // console.log(xiudata['_rawValue'])
          dialogVisibles.value = false
          const res = await Service.tablelist_put({ id: xiudata.value.id, username: obj.form.xiu })
          console.log(res)
          if (res.code == '200') {
            ElMessage({
              message: '修改用户成功',
              type: 'success'
            })
          }
          datas()
        } else {
          console.log('error submit!')
          return false
        }
      })
    }

    const handleDelete = async (index: any, row: any) => {
      console.log(index, row)
      const res = await Service.tablelist_del(row.id)
      console.log(res)
      if (res.code == '200') {
        ElMessage({
          message: '删除用户成功',
          type: 'success'
        })
      }
      datas()
    }
    const handleSizeChange = (val: any) => {
      console.log(`每页 ${val} 条`)
      state.pageSize = val
      let start = (state.currentPage - 1) * state.pageSize
      let end = start + state.pageSize
      state.tableData = state.tableDatalist.slice(start, end)
    }
    const handleCurrentChange = (val: any) => {
      console.log(`当前页: ${val}`)
      state.currentPage = val
      let start = (state.currentPage - 1) * state.pageSize
      let end = start + state.pageSize
      state.tableData = state.tableDatalist.slice(start, end)
    }
    const onSubmit = () => {
      if (formInline.user) {
        let g = state.tableData.filter((item: any) => {
          return item.username.indexOf(formInline.user) > -1
        })
        let start = (state.currentPage - 1) * state.pageSize
        let end = start + state.pageSize
        state.tableData = g.slice(start, end)
        total.value = state.tableData.length
      } else {
        state.tableData = state.tableDatalist
        total.value = state.tableDatalist.length
      }
    }

    const tj = () => {
      dialogVisiblets.value = true
    }
    const validatePass = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('姓名不能为空'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const rules = reactive({
      username: [{ validator: validatePass, trigger: 'blur' }],
      password: [{ validator: validatePass2, trigger: 'blur' }]
    })
    const rules1 = reactive({
      xiu: [{ validator: validatePass3, trigger: 'blur' }]
    })
    const tjqd = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        console.log(valid)
        if (valid) {
          const res = await Service.tablelist_tj({ username: obj.form.username, password: obj.form.password })
          console.log(res)
          if (res.code == '200') {
            ElMessage({
              message: '添加用户成功',
              type: 'success'
            })
          }
          dialogVisiblets.value = false
          datas()
          formEl.resetFields()
        } else {
          console.log('error submit!')
          return false
        }
      })
    }
    const tjq = (formEl: FormInstance | undefined) => {
      dialogVisiblets.value = false
      if (!formEl) return
      formEl.resetFields()
    }
    const fpqd = async () => {
      dialogVisible.value = false
      const res = await Service.tablelist_qxfp({ id: obj1.id, roleid: datavalue.value })
      if (res.code == '200') {
        ElMessage({
          message: '分配角色成功',
          type: 'success'
        })
      }
      datas()
    }
    return {
      formInline,
      total,
      ...toRefs(state),
      ...toRefs(obj),
      ...toRefs(obj1),
      handleCurrentChange,
      handleSizeChange,
      onSubmit,
      handleEdit,
      handleDelete,
      filterTableRef,
      dialogVisible,
      put,
      dialogVisibles,
      qd,
      tj,
      dialogVisiblets,
      tjqd,
      fpqd,
      datavalue,
      dateFliter,
      rules,
      rules1,
      ruleFormRef,
      ruleFormRef1,
      tjq
    }
  }
})
</script>
<style lang="stylus" scoped>
.table-container {
  .form-inline {
    margin: 15px;
    text-align: left;
  }

  .table-list {
    margin: 15px;
  }
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
